package griffin.website;

import griffin.logic.userLogic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.pm.ActivityInfo;

public class contentlist extends Activity{
	private static final String SOAP_ACTION = "http://tempuri.org/addBookmark";
	private static final String METHOD_NAME = "addBookmark";
	private static final String SOAP_ACTION_GETCATEEVALUATION = "http://tempuri.org/getCateEvaluation";
	private static final String METHOD_NAME_GETCATEEVALUATION = "getCateEvaluation";
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String URL = "http://griffin.ciandt.cn/Sservice1.asmx";

	private static final String SOAP_ACTION_GETEVALUATION = "http://tempuri.org/getSiteEvaluation";
	private static final String METHOD_NAME_GETEVALUATION = "getSiteEvaluation";

	private static final String SOAP_ACTION_SETEVALUATION = "http://tempuri.org/setEvaluation";
	private static final String METHOD_NAME_SETEVALUATION = "setEvaluation";

	int siteID=0;
	int cateID=0;

   


	
	private int loginuserid = 0;
	userLogic userlogic = new userLogic(this);
	private List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
	private static final String TAG = "[contentlist]";
	//	String[] stringEvaluationitems = {"sina","baidu","sohu","yahoo"};
	String[] stringEvaluationitems;
	int[] intEvaluationitems ={1,2,3};
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "[onCreate...] ");	
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.contentlist);

		getLoginInfo();
		showCategoryTitle();
		getContent();
	}

	private void getContent()
	{
		prepareGetContent();

		ListView listView = (ListView)findViewById(R.id.lsvContentList);
		listView.setAdapter(new EvaluationAdapter());
		listView.setOnItemClickListener(new ItemClickListener());
		//    	String curcateid = getCurCategoryID();
		//		SimpleAdapter adapter = new SimpleAdapter(this,getContentData(curcateid),R.layout.contentitem,
		//				new String[]{"sitename","rbLevel"},
		//				new int[]{R.id.siteName,R.id.rbLevel});
	}  

	class EvaluationAdapter extends ArrayAdapter<String>{
		public EvaluationAdapter() {
			super(contentlist.this,R.layout.contentitem,stringEvaluationitems);
		}

		public View getView(int position,View convertView,ViewGroup parent)
		{   	
			if(position+1>list.size())return null;

			Map<String,Object> map = list.get(position);
			LayoutInflater inflater = getLayoutInflater();
			View row=inflater.inflate(R.layout.contentitem, parent, false);
			TextView textView = (TextView)row.findViewById(R.id.siteName);
			textView.setText(map.get("sitename").toString());
			RatingBar ratingBar = (RatingBar)row.findViewById(R.id.rbLevel);
			ratingBar.setRating(Float.parseFloat(map.get("rbLevel").toString()));    	

			Log.d(TAG, "[EvaluationAdapter.sitename( "+map.get("sitename").toString() +").siteid("+map.get("siteid").toString() +" ).setRating(" + Float.parseFloat(map.get("rbLevel").toString())+")]");	
			return row;    		
		}

	}

	private void showCategoryTitle() { 	
		Button btnTitle = (Button)findViewById(R.id.btnContentCategoryTitle);
		btnTitle.getBackground().setAlpha(230);
//		btnTitle.setText(getCurCategoryName());
		btnTitle.setText(getCurCategoryName()+getCurCategoryID());
		btnTitle.setOnClickListener(new ButtonTitleClickListener());
	}

	class  ItemClickListener implements OnItemClickListener     
	{     
		public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened      
				View arg1,//The view within the AdapterView that was clicked     
				int arg2,//The position of the view in the adapter     
				long arg3//The row id of the item that was clicked     
		) {      
			LayoutInflater inflater =(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.contentpopup, null);
			final HashMap<String, Object> item=(HashMap<String, Object>) list.get(arg2); 
			
			RatingBar rtbEvaluation =(RatingBar)view.findViewById(R.id.rtbEvaluation);

			//		     final HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);    
			DisplayToast((String)item.get("sitename"));

			try{
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_GETEVALUATION);
				request.addProperty("userID", loginuserid);
				request.addProperty("siteID", Integer.parseInt(item.get("siteid").toString()));

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.dotNet=true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport.call(SOAP_ACTION_GETEVALUATION, envelope);

				Object result = (Object)envelope.getResponse();  
				//float rating = 3.0f;
				float rating = Float.parseFloat(result.toString());
				rtbEvaluation.setRating(rating); 
				
			}catch(Exception ex){
				//TODO maybe need to throw
				ex.printStackTrace(); 
			}



			

			AlertDialog.Builder builder = new AlertDialog.Builder(contentlist.this);
			builder.setView(view);
			builder.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
				public void onClick(DialogInterface dialog, int id) { 
					dialog.cancel(); 
					getContent();
					
				} 
			}); 

			builder.create();
			builder.show();


			Button btnVisit = (Button)view.findViewById(R.id.btnVisit);
			btnVisit.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					openUrl((String)item.get("siteurl"));
				}
			});

			ImageButton imgbtnAddBookmark = (ImageButton)view.findViewById(R.id.imgbtnAddBookmark);
			imgbtnAddBookmark.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					if (loginuserid != 0)
					{
						if (addBookmark((String)item.get("sitename"), (String)item.get("siteurl")))
						{
							DisplayToast("Add bookmark Success!");
						}
						else
						{
							DisplayToast("The bookmark already had added.");
						}
					}
					else
					{
						askloginTip();
					}

				}
			});


			// final TextView  txtvRating=(TextView)view.findViewById(R.id.txtvrating);

			//float rating = 3.0f;

			// rtbEvaluation.setRating(rating); 
			// rtbEvaluation.getRating();
			siteID=Integer.parseInt(item.get("siteid").toString());
			cateID=Integer.parseInt(getCurCategoryID());
			rtbEvaluation.setOnClickListener(new OnClickListener(){
		 		public void onClick(View v){
//		 			if(username.getText().toString().length()==0){	 				
//		 				Toast.makeText(login.this, "Please enter username!", Toast.LENGTH_SHORT).show();
//		 				return;
//		 			}
//		 			if(password.getText().toString().length()==0){
//		 				Toast.makeText(login.this, "Please enter password!", Toast.LENGTH_SHORT).show();
//		 				return;
//		 			}
//		 			goLogin();
		 		}
		 	});
			rtbEvaluation.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

				public void onRatingChanged(RatingBar ratingBar, float rating,
						boolean fromUser) {
					
					try{
						SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_SETEVALUATION);
						request.addProperty("userID", loginuserid);
						request.addProperty("siteID", siteID);
						request.addProperty("cateid",cateID);
						request.addProperty("evaluationNumber",String.valueOf(rating));
						
						if(loginuserid==0){
							askloginTip();
						}else{
						SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
						envelope.dotNet=true;
						envelope.setOutputSoapObject(request);

						HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
						androidHttpTransport.call(SOAP_ACTION_SETEVALUATION, envelope);

						//Object result = (Object)envelope.getResponse();  
						//float rating = 3.0f;
						//float rating = Float.parseFloat(result.toString());
						//rtbEvaluation.setRating(rating); 
						}//end if-else
					}catch(Exception ex){
						//TODO maybe need to throw
						ex.printStackTrace(); 
					}
					
					ratingBar.setRating(rating);   
					Toast.makeText(contentlist.this,   
							"rating:" + String.valueOf(rating),   
							Toast.LENGTH_LONG).show(); 

				}
			});

		}	//onItemClick
		
		
		private void askloginTip() {
			//Toast.makeText(contentlist.this, "You are not sign in..", Toast.LENGTH_SHORT).show();	
			AlertDialog.Builder builder= new AlertDialog.Builder(contentlist.this);
			builder.setTitle("You are not sign in.Login now?").setPositiveButton("Yes!",new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface arg0, int arg1) {
					Intent intent = new Intent(contentlist.this,Login.class);  
					startActivity(intent);  
				}
			});
			builder.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
				public void onClick(DialogInterface dialog, int id) { 
					dialog.cancel(); 									
				} 
			});
			builder.create();
			builder.show();
		}
	}

	class ButtonTitleClickListener implements OnClickListener
	{
		public void onClick(View v)
		{
			
			
			SharedPreferences loginInfo=getSharedPreferences("griffin.website.curcate", 0);
	    	SharedPreferences.Editor editor=loginInfo.edit();
	    	String strCurCategoryID=getCurCategoryID().substring(0, getCurCategoryID().length()-2);
	    	if(loginInfo.contains("curcategoryid"))editor.remove("curcategoryid");
	    	if(loginInfo.contains("curcategoryname"))editor.remove("curcategoryname");
	    	editor.putString("curcategoryid", strCurCategoryID); 	
	    	editor.putString("curcategoryname", getCurCategoryNameNew(strCurCategoryID)); 	
	    	editor.commit();
	    	
	    	contentlist.this.finish();
		}
	}
	
	 private String getCurCategoryNameNew(String curCategoryID){
	    	String resultStr ="";
	    	String databaseFilename = tabframework.DATABASE_PATH + "/" + tabframework.DATABASE_FILENAME;
	    	SQLiteDatabase db;
	    	db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
	    	
	    	Cursor result=null;
	    	if(curCategoryID.length()==1){
	    		result=db.rawQuery(
	    				"SELECT VG_NAME  FROM VG_TopCategories where VG_ID=" + curCategoryID, null);
	    	}else{
	    		result=db.rawQuery(
	    				"SELECT VG_ENGLISH  FROM VG_WebCategories where VG_ID=" + curCategoryID, null);
	    	}
	    	
	    	if (result.moveToFirst())
		    {
		        while (!result.isAfterLast()) { 

		        	resultStr =result.getString(0);
		            result.moveToNext(); 
		          }
		    }
		    result.close(); 
		    db.close();
			
			return resultStr;
	    }
	

	private Boolean addBookmark(String bookmarkName, String bookmarkUrl)
	{
		Boolean isSuccess = false;

		if (loginuserid != 0)
		{
			try{
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

		        request.addProperty("userid", loginuserid);
		        request.addProperty("bookmarkName", bookmarkName);
		        request.addProperty("bookmarkUrl", bookmarkUrl);
	
		        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		        envelope.dotNet=true;
		        envelope.setOutputSoapObject(request);
	
		        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		        androidHttpTransport.call(SOAP_ACTION, envelope);
	
		        Object result = (Object)envelope.getResponse();    
		        if (Integer.parseInt(result.toString()) == 1)
		        {
		        	isSuccess = true;
		        }

			}catch(Exception ex){
				//TODO maybe need to throw
				ex.printStackTrace(); 
			}
		}

		return isSuccess;
	}

	private void getLoginInfo() {
		AtomicReference<String> strUsername=new AtomicReference<String>("");
		AtomicReference<String> strPassword=new AtomicReference<String>("");
		AtomicInteger userid=new AtomicInteger(0);
		if(userlogic.getLoginUser(strUsername, strPassword, userid)){
			loginuserid = userid.get();
		}
	}

	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent); 
	}

	public void DisplayToast(String str)
	{
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	private String getCurCategoryID() {
		SharedPreferences curcateInfo = getSharedPreferences("griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryid", "");
	}

	private String getCurCategoryName() {
		SharedPreferences curcateInfo = getSharedPreferences("griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryname", "");
	}

	private void prepareGetContent(){
		list.clear();
		String cateid = getCurCategoryID();
		//get rbLevel 
		Map<String,Object> evalEvaluations  = getrbLevels(cateid);
		Log.d(TAG, "[getrbLevels( "+cateid +" ).size(" + evalEvaluations.size()+")]");	 

		String databaseFilename = tabframework.DATABASE_PATH + "/" + tabframework.DATABASE_FILENAME;
		SQLiteDatabase db;

		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		Cursor result=db.rawQuery("SELECT VG_ID, VG_ENGLISH, VG_HTTPURL FROM VG_WebSites where VG_PARENT = " + cateid, null); 
		if (result.moveToFirst())
		{
			while (!result.isAfterLast()) {
				String siteid = result.getString(0);
				String sitename = result.getString(1);
				String siteurl = result.getString(2);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sitename", sitename);
				map.put("siteurl", siteurl);
				map.put("siteid", siteid);
				if(evalEvaluations.containsKey(siteid)){
					map.put("rbLevel", evalEvaluations.get(siteid));
				}else{
					map.put("rbLevel", "0");
				}
				list.add(map);
				result.moveToNext(); 
			}
		}
		result.close(); 
		db.close();  
		stringEvaluationitems=new String[list.size()];

		Log.d(TAG, "[lists( "+cateid +" ).size(" + list.size()+")]");	 		
	}

	private Map<String, Object> getrbLevels(String curcateid){
		Map<String, Object> map = new HashMap<String, Object>();

		try{
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_GETCATEEVALUATION);
			request.addProperty("cateID", curcateid);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.dotNet=true;
			envelope.setOutputSoapObject(request);

			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
			androidHttpTransport.call(SOAP_ACTION_GETCATEEVALUATION, envelope);

			Object result = (Object)envelope.getResponse(); 	        	
			JSONObject jsonObj = new JSONObject(result.toString());
			JSONArray evaluationkArr = jsonObj.getJSONArray("evaluation");

			for(int i = 0; i < evaluationkArr.length(); i++)
			{
				map.put(evaluationkArr.getJSONObject(i).getString("siteid"), evaluationkArr.getJSONObject(i).getString("evaluationnumber"));            	
			}	        
		}catch(Exception ex){
			String errmsg =ex.toString();
			errmsg +="asd";
		}


		return map;
	}
	@Override 
	public boolean onTouchEvent(MotionEvent evt)  
	{  
		if(evt.getAction() == MotionEvent.ACTION_DOWN)  
		{  
			DisplayToast("on touch event");
		}  
		return true;  
	}  

}
